package top.archiesean.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author ArchieSean
 * @description 网关限流策略
 * @date 2024-02-18
 */
@Configuration(proxyBeanMethods = false)
public class RateLimiterConfiguration {

    /**
     * 基于客户端ip进行限流
     *
     * @return 自定义限流策略
     */
    @Bean
    public KeyResolver remoteAddrKeyResolver() {
        // @formatter:off
        return exchange -> Mono.just(Objects.requireNonNull(
                Objects.requireNonNull(exchange.getRequest()).getRemoteAddress())
                .getAddress().getHostAddress());
        // @formatter:on
    }
}
